package com.hdcircles.autoform.ui.label.fragment;

import android.app.ActivityOptions;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.StaggeredGridLayoutManager;
import android.support.v7.widget.helper.ItemTouchHelper;
import android.view.View;

import com.google.gson.Gson;
import com.hdcircles.autoform.R;
import com.hdcircles.autoform.app.Constants;
import com.hdcircles.autoform.base.BaseFragment;
import com.hdcircles.autoform.model.bean.ChooseQuestionBean;
import com.hdcircles.autoform.model.bean.FormBean;
import com.hdcircles.autoform.model.bean.QuestionBean;
import com.hdcircles.autoform.presenter.MyLabelsPresenter;
import com.hdcircles.autoform.presenter.contract.MyLabelsContract;
import com.hdcircles.autoform.ui.label.activity.FillFormActivity;
import com.hdcircles.autoform.ui.label.activity.FormListActivity;
import com.hdcircles.autoform.ui.label.activity.UserListActivity;
import com.hdcircles.autoform.ui.label.adapter.FormAdapter;
import com.hdcircles.autoform.ui.main.activity.MainActivity;
import com.hdcircles.autoform.util.SharedPreferenceUtil;
import com.hdcircles.autoform.util.SnackbarUtil;
import com.hdcircles.autoform.util.SystemUtil;
import com.hdcircles.autoform.widget.DefaultItemTouchHelpCallback;
import com.melnykov.fab.FloatingActionButton;
import com.orhanobut.logger.Logger;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;

/**
 * Created by hdcircles on 2016/9/27.
 */

public class MyLabelsFragment extends BaseFragment<MyLabelsPresenter> implements MyLabelsContract.View
        , FormAdapter.FillClickListener,FormAdapter.ViewClickListener,FormAdapter.onSendClickListener,FormAdapter.onShareClickListener{

    @BindView(R.id.rv_form)
    RecyclerView rvForm;

    @BindView(R.id.refreshLayout)
    SwipeRefreshLayout refreshLayout;

    private static final int SPAN_COUNT = 2;

    private List<FormBean> formBeanList;


    private FormAdapter adapter;

    private DefaultItemTouchHelpCallback mCallback;

    @Override
    protected void initInject() {
        getFragmentComponent().inject(this);
    }

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_my_label;
    }

    @Override
    protected void initEventAndData() {
        formBeanList=new ArrayList<>();
        adapter = new FormAdapter(formBeanList);
        StaggeredGridLayoutManager staggeredGridLayoutManager=new StaggeredGridLayoutManager(SPAN_COUNT,StaggeredGridLayoutManager.VERTICAL);
        staggeredGridLayoutManager.setGapStrategy(StaggeredGridLayoutManager.GAP_HANDLING_NONE);
//        rvForm.setLayoutManager(new GridLayoutManager(getContext(),SPAN_COUNT));
        rvForm.setLayoutManager(new LinearLayoutManager(getActivity()));
        rvForm.setAdapter(adapter);
        adapter.setOnFillClickListener(this);
        adapter.setOnViewClickListener(this);
        adapter.setOnSendClickListener(this);
        adapter.setOnShareClickListener(this);
        mCallback=new DefaultItemTouchHelpCallback(new DefaultItemTouchHelpCallback.OnItemTouchCallbackListener() {
            @Override
            public void onSwiped(final int adapterPosition) {
                //滑动删除的时候，从数据库，数据源移除，并刷新UI
                if (null!=formBeanList){
                    new AlertDialog.Builder(getActivity())
                            .setMessage("确认删除当前表单？")
                            .setPositiveButton(R.string.confirm, new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialogInterface, int i) {
                                    mPresenter.deleteFormData(formBeanList.get(adapterPosition).getFormId());
                                    formBeanList.remove(adapterPosition);
                                    adapter.notifyItemRemoved(adapterPosition);
                                }
                            })
                            .setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialogInterface, int i) {
                                    adapter.notifyDataSetChanged();
                                }
                            })
                            .setCancelable(false)
                            .show();

                }
            }

            @Override
            public boolean onMove(int srcPosition, int targetPosition) {
                if (null!=formBeanList){
                    //TODO 更换数据库中item的位置
                    boolean isPlus=srcPosition<targetPosition;

                }
                return false;
            }
        });
        mCallback.setCanSwipe(false);
        ItemTouchHelper itemTouchHelper=new ItemTouchHelper(mCallback);
        itemTouchHelper.attachToRecyclerView(rvForm);
        refreshLayout.post(new Runnable() {
            @Override
            public void run() {
                refreshLayout.setRefreshing(true);
            }
        });
        refreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                mPresenter.getFormData();
            }
        });
        FloatingActionButton fabAdd = ((MainActivity) getActivity()).getFabAdd();
        fabAdd.attachToRecyclerView(rvForm);
    }

    @Override
    public void saveDefaultDataSuccess() {
        SharedPreferenceUtil.setDefaultDataState(true);
    }

    @Override
    public void showEmpty() {
        formBeanList.clear();
        mPresenter.getSharedFormData();
    }

    @Override
    public void showContent(List<FormBean> formBeanList) {
        this.formBeanList.clear();
        this.formBeanList.addAll(formBeanList);
        Logger.json(new Gson().toJson(formBeanList));
        adapter.notifyDataSetChanged();
//        refreshLayout.setRefreshing(false);
        mPresenter.getSharedFormData();
    }

    @Override
    public void showSharedContent(List<FormBean> formBeanList) {
        this.formBeanList.addAll(formBeanList);
        adapter.notifyDataSetChanged();
        refreshLayout.setRefreshing(false);
    }

    @Override
    public void onResume() {
        super.onResume();
        mPresenter.getFormData();
    }

    @Override
    public void onFill(FormBean form,View shareView) {
        Intent intent=new Intent(getActivity(), FillFormActivity.class);
        Bundle bundle=new Bundle();
        bundle.putParcelable("form",form);
        intent.putExtras(bundle);
        intent.putExtra("isEmpty",true);
        ActivityOptions options=ActivityOptions.makeSceneTransitionAnimation(mActivity,shareView,"shareView");
        getActivity().startActivity(intent,options.toBundle());
    }

    @Override
    public void onView(String id,String creatorEmail,View shareView) {
        Intent intent=new Intent(getActivity(), FormListActivity.class);
        intent.putExtra("formId",id);
        intent.putExtra("creatorEmail",creatorEmail);
        ActivityOptions options=ActivityOptions.makeSceneTransitionAnimation(mActivity,shareView,"shareView");
        getActivity().startActivity(intent,options.toBundle());
    }

    @Override
    public void onSend(FormBean form, View view) {
        Intent intent=new Intent(getActivity(), UserListActivity.class);
        Bundle bundle=new Bundle();
        bundle.putParcelable("form",form);
        intent.putExtras(bundle);
        ActivityOptions options=ActivityOptions.makeSceneTransitionAnimation(mActivity,view,"shareView");
        getActivity().startActivity(intent,options.toBundle());
    }

    @Override
    public void showError(String msg) {
//        SnackbarUtil.showShort(rvForm,msg);
        refreshLayout.setRefreshing(false);

    }

    @Override
    public void onShare(FormBean form, View view) {
        Intent intent=new Intent(getActivity(), UserListActivity.class);
        Bundle bundle=new Bundle();
        bundle.putParcelable("form",form);
        intent.putExtras(bundle);
        intent.putExtra("isShare",true);
        ActivityOptions options=ActivityOptions.makeSceneTransitionAnimation(mActivity,view,"shareView");
        getActivity().startActivity(intent,options.toBundle());
    }
}
